package org.kl.bf.service.basic;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.Organization;
import org.kl.bf.repository.basic.OrganizationDao;
import org.kl.bf.service.ServiceException;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Collections3;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class OrganizationService {

	private OrganizationDao organizationDao;

	@Autowired
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}

	public Organization getOrganization(String guid) {
		return organizationDao.findOne(guid);
	}

	public void saveOrganization(Organization entity) {
		organizationDao.save(entity);
	}

	public void deleteOrganization(String guid) {
		organizationDao.delete(guid);
	}

	public Organization findByOrgName(String orgName) {
		return organizationDao.findByOrgName(orgName);
	}

	public int childrenCount(final String pcode) {
		Specification<Organization> spec = new Specification<Organization>() {
			public Predicate toPredicate(Root<Organization> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate p2 = cb.equal(root.get("parentOrgId").as(String.class), pcode);
				query.where(p2);
				return query.getRestriction();
			}
		};
		return (int) organizationDao.count(spec);
	}

	public int batchDeleteOrganization(String ids) {
		String[] idArray = ids.split(",");
		int deletedCount = 0;
		for (String id : idArray) {
			if (StringUtils.isBlank(id)) {
				continue;
			}
			Organization organization = organizationDao.findOne(id);
			int count = childrenCount(organization.getOrgNo());
			if (count != 0) {
				throw new ServiceException(organization.getOrgNo() + "--" + organization.getOrgName() + "不是叶子节点，不能删除");
			}
			deletedCount++;
		}
		for (String id : idArray) {
			if (StringUtils.isBlank(id)) {
				continue;
			}
			organizationDao.delete(id);
		}
		return deletedCount;
	}

	public List<Organization> findById(String id) {
		return organizationDao.findById(id);
	}

	public List<Organization> findByOrgNo(String orgNo) {
		return organizationDao.findByOrgNo(orgNo);
	}

	public List<Organization> findByParentOrgId(String parentOrgId) {
		return organizationDao.findByParentOrgId(parentOrgId);
	}

	public List<Organization> getAllOrganization() {
		return organizationDao.findAll(new Sort(Direction.ASC, "orgNo"));
	}

	// 获取根节点
	public List<Organization> findRoot() {
		return organizationDao.findRoot();
	}

	// 获取子节点
	public List<Organization> findByOrganizationsParentOrgIdIn(Collection<String> parentOrgId) {
		if (Collections3.isEmpty(parentOrgId)) {
			return null;
		}
		return organizationDao.findByParentOrgIdIn(parentOrgId);
	}

	public Page<Organization> getPbs(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<Organization> spec = buildSpecification(searchParams);

		return organizationDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Organization> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<Organization> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), Organization.class);
		return spec;
	}

}
